// pages/usercenter/memberapply/memberapply.js
const { registerWx } = require('../../../services/user/auth');
const { backendApiUrl } = require('../../../utils/config');
import { apiRequest } from '../../../services/_utils/apiRequest';

const globalModel = require('../../../model/global');

Page({
  data: {
    name: '',
    phone: '',
    inviteCode: '',
    servicePhone: '',
  },

  onNameInput(event) {
    this.setData({ name: event.detail.value });
  },

  onInviteCodeInput(event) {
    this.setData({ inviteCode: event.detail.value });
  },

  onLoad() {
    const servicePhone = globalModel.getServicePhone() || '138xxxx';    
    this.setData({
      servicePhone: servicePhone,
    });
  },

  async onConfirmPhone(e) {
    const { code } = e.detail; // 获取动态令牌

    if (!this.data.name) {
      wx.showToast({
        title: '姓名不能为空',
        icon: 'none',
      });
      return;
    }

    if (!this.data.inviteCode) {
      wx.showToast({
        title: '邀请码不能为空',
        icon: 'none',
      });
      return;
    }

    if (!code) {
      wx.showToast({
        title: '用户取消了授权',
        icon: 'none',
      });
      return;
    }

    try {
      // 调用后端服务接口，获取手机号
      const phoneRes = await apiRequest({
        url: `${backendApiUrl}/wechat/phone`,
        method: 'POST',
        data: { code }, // 传递动态令牌到后端
        useToken: false,
      });
      this.setData({ phone: phoneRes.phoneNumber });

      // 获取微信登录 code
      const loginRes = await wx.login();
      const codeWx = loginRes.code;

      if (!codeWx) {
        throw new Error('获取微信登录 code 失败');
      }

      const { name, phone, inviteCode } = this.data;
      const userData = await registerWx({
        code:codeWx,
        nickname: name,
        phone,
        inviteCode,
      });

      // 注册成功
      wx.showToast({
        title: '注册成功',
        icon: 'success',
      });

      this.setData({ showDialog: false });
      wx.navigateBack();
    } catch (err) {
      console.error('注册失败:', err);
  
      // 捕获错误并显示弹框提示
      wx.showModal({
        title: '错误',
        content: err.message || '注册失败，请重试',
        showCancel: false, // 不显示取消按钮
        confirmText: '确定',
      });
    }
  },

  onBack() {
    wx.navigateBack(); 
  },
});
